<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.Name"
        placeholder="备注名称"
        style="width: 150px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-input
        v-model="listQuery.Title"
        placeholder="主题"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select
        v-model="listQuery.stype"
        style="width: 110px"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option
          v-for="item in stypeOptions"
          :key="item.key"
          :label="item.label"
          :value="item.key"
        />
      </el-select>

      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        查询
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
    >
      <!-- <el-table-column
        label="ID"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
        :class-name="getSortClass('id')"
      >
        <template slot-scope="{ row }">
          <span>{{ row.Id }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="备注名称" width="130px">
        <template slot-scope="{ row }">
          <span>{{ row.Name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="投放时间" width="110px" align="center">
        <template slot-scope="{ row }">
          <span
            >{{ row.Stime | parseTime("{m}-{d}") }}_{{
              row.Etime | parseTime("{m}-{d}")
            }}</span
          >
        </template>
      </el-table-column>
      <el-table-column label="文案" width="238px">
        <template slot-scope="{ row }">
          <span>{{ row.Title }}-{{ row.Desc }}</span>
        </template>
      </el-table-column>

      <el-table-column label="状态" width="100px">
        <template slot-scope="{ row }">
          <span>{{ row.AdId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="系统状态" width="180px">
        <template slot-scope="{ row }">
          <span>{{ row.StatusMsg }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核信息" width="180px">
        <template slot-scope="{ row }">
          <span>{{ row.Rejessage }}</span>
        </template>
      </el-table-column>
      <el-table-column label="曝光" width="60px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.ViewCount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="当前花费" width="180px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.Pricestr }}</span>
        </template>
      </el-table-column>
      <el-table-column label="冻结资金" width="180px" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.FreezingPricestr }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="100px" align="center">
        <template slot-scope="{ row }">
          <span class="link-type">{{
            row.CreatedAt | parseTime("{m}-{d} {h}:{i}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="showReviewer"
        label="Reviewer"
        width="110px"
        align="center"
      >
        <template slot-scope="{ row }">
          <span style="color: red">{{ row.reviewer }}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column label="代理品牌" align="center" width="95">
        <template slot-scope="{ row }"> </template>
      </el-table-column> -->
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <!-- ------------------------- -->
    <el-dialog :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="店名称" prop="TagName">
          <el-input v-model="temp.TagName" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          修改
        </el-button>
      </div>
    </el-dialog>

    <!-- ======================= -->
    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false"
          >Confirm</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchAdList } from "@/api/mdlist";
import waves from "@/directive/waves"; // waves directive
import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: "CN", display_name: "China" },
  { key: "US", display_name: "USA" },
  { key: "JP", display_name: "Japan" },
  { key: "EU", display_name: "Eurozone" },
];

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name;
  return acc;
}, {});

export default {
  name: "ComplexTable",
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "info",
        deleted: "danger",
      };
      return statusMap[status];
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type];
    },
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        my: "1",
        page: 1,
        limit: 10,
        importance: undefined,
        title: undefined,
        type: undefined,
        stype: "all",
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      stypeOptions: [
        { label: "全部", key: "all" },
        { label: "正在进行", key: "ing" },
        { label: "未开始", key: "wait" },
        { label: "已结束", key: "end" },
      ],
      statusOptions: ["published", "draft", "deleted"],
      showReviewer: false,
      // ======================================================
      temp: {
        id: undefined,
        TagName: "",
      },
      dialogFormVisible: false,
      dialogStatus: "",

      dialogPvVisible: false,
      rules: {
        TagName: [
          { required: true, message: "店名称不可为空", trigger: "blur" },
        ],
      },

      downloadLoading: false,
      dialogFormAdRecharge: false,
      mdid: null,
    };
  },
  created() {
    this.mdid = this.$route.query && this.$route.query.id;
    this.getList();
  },
  methods: {
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp);
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleUpdateAdRecharge(row) {
      this.tempad = Object.assign({}, row); // copy obj
      this.dialogFormAdRecharge = true;
      this.$nextTick(() => {
        this.$refs["dataFormad"].clearValidate();
      });
    },
    getList() {
      this.listLoading = true;
      fetchAdList(this.listQuery, { Mdid: this.mdid })
        .then((response) => {
          this.list = response.data.list;
          this.total = response.data.total;

          // Just to simulate the time of the request
          // this.listLoading = false;
          setTimeout(() => {
            this.listLoading = false;
          }, 100);
        })
        .catch(function () {
          console.log("aaaaaaaaaaaa9999999999999");
        });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: "操作Success",
        type: "success",
      });
      row.status = status;
    },
    adpage(row, status) {
      // console.log(row, "aaaaaaaaaaaaaaaaaaaaaa");
      this.$router.push({ name: "cbd-adpage", query: { id: row.Id } });
    },
    addad(row, status) {
      // console.log(row, "aaaaaaaaaaaaaaaaaaaaaa");
      this.$router.push({ name: "cbd-addad", query: { id: row.Id } });
    },
    adlist(row, status) {
      // console.log(row, "aaaaaaaaaaaaaaaaaaaaaa");
      this.$router.push({ name: "cbd-adlist", query: { id: row.Id } });
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sort = "+id";
      } else {
        this.listQuery.sort = "-id";
      }
      this.handleFilter();
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: "",
        timestamp: new Date(),
        title: "",
        status: "published",
        type: "",
      };
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    createData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024; // mock a id
          this.temp.author = "vue-element-admin";
          createArticle(this.temp).then(() => {
            this.list.unshift(this.temp);
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "Created Successfully",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp);
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp);

          tagMdName({ TagName: tempData.TagName }, { Mdid: tempData.Id }).then(
            (response) => {
              this.listLoading = false;
              if (response.code == 0) {
                this.dialogFormVisible = false;
                this.getList();
              }
            }
          );
          // tempData.timestamp = +new Date(tempData.timestamp); // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          // updateArticle(tempData).then(() => {
          //   const index = this.list.findIndex((v) => v.id === this.temp.id);
          //   this.list.splice(index, 1, this.temp);
          //   this.dialogFormVisible = false;
          //   this.$notify({
          //     title: "Success",
          //     message: "Update Successfully",
          //     type: "success",
          //     duration: 2000,
          //   });
          // });
        }
      });
    },
    updateDataad() {
      this.$refs["dataFormad"].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.tempad);
          console.log(
            tempData,
            "aaaaaaaaaaaaaaaaaaaaaaaaaa",
            Number(tempData.AddPrice) * 100
          );

          adRecharge(
            { Price: Number(tempData.AddPrice) * 100 },
            { Mdid: tempData.Id }
          ).then((response) => {
            this.listLoading = false;
            if (response.code == 0) {
              this.dialogFormAdRecharge = false;
              this.getList();
            }
          });
        }
      });
    },
    handleDelete(row, index) {
      this.$notify({
        title: "Success",
        message: "Delete Successfully",
        type: "success",
        duration: 2000,
      });
      this.list.splice(index, 1);
    },

    getSortClass: function (key) {
      const sort = this.listQuery.sort;
      return sort === `+${key}` ? "ascending" : "descending";
    },
    toAddMdpage: function () {
      this.$router.push({ name: "cbd-searchmdlist" });
    },
  },
};
</script>
